package uk.ac.cam.cl.android.jwdb;

import android.content.Context;
import android.util.Log;

import com.ubhave.sensormanager.ESException;
import com.ubhave.sensormanager.ESSensorManager;
import com.ubhave.sensormanager.ESSensorManagerInterface;
import com.ubhave.sensormanager.SensorDataListener;
import com.ubhave.sensormanager.config.GlobalConfig;
import com.ubhave.sensormanager.config.sensors.pull.LocationConfig;
import com.ubhave.sensormanager.data.SensorData;
import com.ubhave.sensormanager.sensors.SensorUtils;

public class SensorThread implements SensorDataListener
{
	//private final int sensorType;
	//private final SensorDataUI userInterface;

	private ESSensorManagerInterface sensorManager;
	//private final JSONFormatter formatter;

	private int sensorSubscriptionId;
	private boolean isSubscribed;

	public SensorThread(Context context)
	{
		//this.sensorType = sensorType;
		//this.userInterface = userInterface;
		isSubscribed = false;
		
		//formatter = DataFormatter.getJSONFormatter(context, sensorType);
		try
		{
			sensorManager = ESSensorManager.getSensorManager(context);
			sensorManager.setGlobalConfig(GlobalConfig.LOW_BATTERY_THRESHOLD, 25);
		}
		catch (ESException e)
		{
			e.printStackTrace();
		}
	}

	public void subscribeToSensorData()
	{
		try
		{
			sensorSubscriptionId = sensorManager.subscribeToSensorData(SensorUtils.SENSOR_TYPE_ACCELEROMETER, this);
			isSubscribed = true;
		}
		catch (ESException e)
		{
			e.printStackTrace();
		}
	}

	public void unsubscribeFromSensorData()
	{
		try
		{
			sensorManager.unsubscribeFromSensorData(sensorSubscriptionId);
			isSubscribed = false;
		}
		catch (ESException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void onDataSensed(SensorData data)
	{
		//userInterface.updateUI(formatter.toJSON(data).toJSONString());
		Log.e("Hi", "Testing data");
	}

	public String getSensorName()
	{
		try
		{
			return SensorUtils.getSensorName(SensorUtils.SENSOR_TYPE_ACCELEROMETER);
		}
		catch (ESException e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public boolean isSubscribed()
	{
		return isSubscribed;
	}

	@Override
	public void onCrossingLowBatteryThreshold(boolean isBelowThreshold)
	{
		try
		{
			if (isBelowThreshold)
			{
				//userInterface.updateUI("Sensing stopped: low battery");
				sensorManager.pauseSubscription(sensorSubscriptionId);
			}
			else
			{
				//userInterface.updateUI("Sensing unpaused: battery healthy");
				sensorManager.unPauseSubscription(sensorSubscriptionId);
			}
		}
		catch (ESException e)
		{
			e.printStackTrace();
		}

	}

}